package org.lansir.af.ui;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.lansir.af.R;
import org.lansir.af.database.DataRowActivity;
import org.lansir.af.database.DataRowActivityParticipator;
import org.lansir.af.database.DataTable;
import org.lansir.af.database.Database;
import org.lansir.af.dataview.DataViewActivityParticipator;
import org.lansir.af.dataview.DataViewItem;
import org.lansir.af.dataview.DataViewItemActivityParticipator;
import org.lansir.af.gtalk.service.Contact;
import org.lansir.af.gtalk.service.Message;
import org.lansir.af.gtalk.service.aidl.IChat;
import org.lansir.af.gtalk.service.aidl.IChatManager;
import org.lansir.af.gtalk.service.aidl.IXmppFacade;
import org.lansir.af.util.RepeatData;
import org.lansir.af.util.Utils;
import org.lansir.af.view.DatePickerWheel;
import org.lansir.af.view.DatePickerWheel.OnDateWheelSetListener;
import org.lansir.af.view.TimePickerWheel;
import org.lansir.af.view.TimePickerWheel.OnTimeWheelSetListener;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;

public class ScheduleActivityFragment extends CommonFragment {
	public static final String TAG = "ScheduleActivityFragment";

	private static final Intent SERVICE_INTENT = new Intent();
	static {
		SERVICE_INTENT.setComponent(new ComponentName("org.lansir.af", "org.lansir.af.gtalk.GtalkService"));
	}

	private IXmppFacade mXmppFacade = null;
	private IChatManager mChatManager = null;
	private GtalkServiceConnection mServiceConn = new GtalkServiceConnection();
	private boolean mBinded = false;

	private final static int REQUESTCODE_CONTACTS = 0x442;

	private DataRowActivity dataRowActivity = null;
	private DataTable dataTableActivity = null;
	private DataRowActivityParticipator dataRowActivityParticipator = null;
	private DataTable dataTableActivityParticipator = null;
	private DataViewActivityParticipator dataViewActivityParticipator;

	private EditText etActvitySubject;
	private EditText etActivityLocaiton;
	private Button btnActivityStartDate;
	private Button btnActvityStartTime;
	private Spinner spinActivityRingerMode;
	private Button btnActivityRepeat;
	private EditText etActivityAnticipator;

	private CheckBox cbActivityAlarm;
	private long lNewRowId;

	private ArrayList<Contact> mSelectedContact = new ArrayList<Contact>();

	// 手机模式的适配器
	private ArrayAdapter<CharSequence> adapterRingerMode = null;
	// 响铃模式:默认为标准模式
	private String sOrganizer = "";
	private int iRingerMode = AudioManager.RINGER_MODE_NORMAL;
	// repeat data
	private int iRepeatType = -1;
	private int iRepeatEvery = 0;
	private int iSnooze;
	private int iSnoozeCount;
	private int iActionClear;
	private Calendar dateEndOn = null;
	private Calendar calendar = Calendar.getInstance();
	private Calendar dateStart = Calendar.getInstance();

	private LayoutInflater mInflater;

	// private ArrayList<Participator> mSelectedParticipators = new
	// ArrayList<Participator>();
	// private ProgressDialog progressDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		dataRowActivity = new DataRowActivity(userdb);
		dataTableActivity = new DataTable(dataRowActivity);

		dataRowActivityParticipator = new DataRowActivityParticipator(userdb);
		dataTableActivityParticipator = new DataTable(dataRowActivityParticipator);
		
		// check startup mode and open data
		if (getStartMode() == StartMode.EDIT)
			if (!openDataForEdit(dataTableActivity))
				getActivity().finish();
		this.setHasOptionsMenu(true);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View viewRoot = inflater.inflate(R.layout.fragment_activity, null);
		mInflater = inflater;
		etActvitySubject = (EditText) viewRoot.findViewById(R.id.etActivitySubject);
		etActivityLocaiton = (EditText) viewRoot.findViewById(R.id.etActivityLocaiton);
		btnActivityStartDate = (Button) viewRoot.findViewById(R.id.btnActivityStartDate);
		btnActvityStartTime = (Button) viewRoot.findViewById(R.id.btnActvityStartTime);
		spinActivityRingerMode = (Spinner) viewRoot.findViewById(R.id.spinActivityRingerMode);
		btnActivityRepeat = (Button) viewRoot.findViewById(R.id.btnActivityRepeat);
		etActivityAnticipator = (EditText) viewRoot.findViewById(R.id.etActivityParticipator);

		btnActivityStartDate.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				Date date = new Date();
				// 创建一个Date实例
				calendar.setTime(date);
				// 获得日历中的 year month day
				DatePickerWheel dlg = new DatePickerWheel(getActivity(), mDateSetListener, dateStart.get(Calendar.YEAR), dateStart.get(Calendar.MONTH),
						dateStart.get(Calendar.DAY_OF_MONTH));
				Log.v(TAG, "DAY_OF_MONTH:" + dateStart.get(Calendar.DAY_OF_MONTH));
				// DatePickerDialog dlg = new DatePickerDialog(getActivity(),
				// mDateSetListener, dateStart.get(Calendar.YEAR),
				// dateStart.get(Calendar.MONTH),
				// dateStart.get(Calendar.DAY_OF_MONTH));
				// 新建一个DatePickerDialog 构造方法中
				// （设备上下文，OnDateSetListener时间设置监听器，默认年，默认月，默认日）
				dlg.show();

			}
		});

		btnActvityStartTime.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Date date = new Date();
				// 创建一个Date实例
				calendar.setTime(date);
				TimePickerWheel dlg = new TimePickerWheel(getActivity(), mTimeSetListener, dateStart.get(Calendar.HOUR_OF_DAY), dateStart.get(Calendar.MINUTE));
				// TimePickerDialog dlg = new TimePickerDialog(getActivity(),
				// mTimeSetListener, dateStart.get(Calendar.HOUR_OF_DAY),
				// dateStart
				// .get(Calendar.MINUTE), true);
				// 新建一个DatePickerDialog 构造方法中
				// （设备上下文，OnDateSetListener时间设置监听器，默认年，默认月，默认日）
				dlg.show();
			}
		});

		adapterRingerMode = ArrayAdapter.createFromResource(getActivity(), R.array.ringerMode, android.R.layout.simple_spinner_item);
		adapterRingerMode.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinActivityRingerMode.setAdapter(adapterRingerMode);
		spinActivityRingerMode.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				iRingerMode = spinActivityRingerMode.getSelectedItemPosition();
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}

		});
		spinActivityRingerMode.setSelection(iRingerMode);

		btnActivityRepeat.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				openRepeatDialog();
			}
		});

		cbActivityAlarm = (CheckBox) viewRoot.findViewById(R.id.cbActivityAlarm);

		dateEndOn = Calendar.getInstance();

		etActivityAnticipator.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent("android.intent.action.ACTION_MODE_ACTIVITYCONTACTS");
				startActivityForResult(intent, REQUESTCODE_CONTACTS);
			}
		});

		etActivityAnticipator.setOnFocusChangeListener(new View.OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					startActivityForResult(new Intent("android.intent.action.ACTION_MODE_ACTIVITYCONTACTS"), REQUESTCODE_CONTACTS);
				}

			}
		});

		initStates();

		return viewRoot;
	}

	protected void initStates() {
		// check startup mode and open data
		Date date = new Date();
		calendar.setTime(date);
		dateStart.setTime(date);
		if (getStartMode() == StartMode.NEW) {
			Intent intent = getActivity().getIntent();
			int year = intent.getIntExtra("Year", -1);
			int month = intent.getIntExtra("Month", -1);
			int day = intent.getIntExtra("Day", -1);
			if (year != -1 && month != -1 && day != -1) {
				calendar.set(Calendar.YEAR, year);
				calendar.set(Calendar.MONTH, month);
				calendar.set(Calendar.DAY_OF_MONTH, day);

				dateStart.set(Calendar.YEAR, year);
				dateStart.set(Calendar.MONTH, month);
				dateStart.set(Calendar.DAY_OF_MONTH, day);
			}
			iSnooze = 0;
			iSnoozeCount = 0;
			iActionClear = SnoozeAction.convertToInt(SnoozeAction.Clear);
			updateStartDate(calendar);
			updateStartTime(calendar);

			iRepeatType = 0; // none
			iRepeatEvery = 1;
			dateEndOn.setTimeInMillis(0); // no end date

			sOrganizer = utils.getResStr(R.string.strActivityOrganizerMe);
		} else if (getStartMode() == StartMode.EDIT) {
			dataViewActivityParticipator = new DataViewActivityParticipator(userdb, requestedRowId());
			dataViewActivityParticipator.reloadTable();

			// TODO

			setContacts(dataViewActivityParticipator.getRowsForTotal());

			etActvitySubject.setText(dataRowActivity.getSubject());
			etActivityLocaiton.setText(dataRowActivity.getLocation());
			updateStartDate(dataRowActivity.getStartDate());
			updateStartTime(dataRowActivity.getStartDate());
			spinActivityRingerMode.setSelection(dataRowActivity.getRingerMode());
			cbActivityAlarm.setChecked(dataRowActivity.getAlarm());
			sOrganizer = dataRowActivity.getOrganizer();
			iRepeatType = dataRowActivity.getRepeat().getRepeatTypeAsInt();
			iRepeatEvery = dataRowActivity.getRepeat().getEvery();
			dateEndOn.setTimeInMillis(dataRowActivity.getRepeat().getEndOnDate().getTimeInMillis());
			iSnooze = dataRowActivity.getSnooze();
			iSnoozeCount = dataRowActivity.getSnoozeCount();
			iActionClear = dataRowActivity.getActionClear();
			etActivityAnticipator.setEnabled(false);

		}
		updateRepeatInfo();
		etActvitySubject.requestFocus();
		if (getStartMode() == StartMode.EDIT)
			etActvitySubject.setSelection(etActvitySubject.length());

	}

	@Override
	public void onPause() {
		if (mBinded) {
			getActivity().unbindService(mServiceConn);
			mBinded = false;
		}
		super.onPause();
	}

	@Override
	public void onResume() {
		if (!mBinded && mGtalkApplication.isConnected()) {
			mBinded = getActivity().bindService(SERVICE_INTENT, mServiceConn, Context.BIND_AUTO_CREATE);
		}
		super.onResume();
	}

	private OnDateWheelSetListener mDateSetListener = new OnDateWheelSetListener() {
		@Override
		public void onDateWheelChanged(int year, int monthOfYear, int dayOfMonth) {
			updateStartDate(year, monthOfYear, dayOfMonth);
		}

	};

	private OnTimeWheelSetListener mTimeSetListener = new OnTimeWheelSetListener() {
		@Override
		public void onTimeWheelChanged(int hourOfDay, int minute) {
			updateStartTime(hourOfDay, minute);
		}
	};

	private void updateStartDate(Calendar cal) {
		updateStartDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
	}

	private void updateStartDate(int year, int monthOfYear, int dayOfMonth) {
		dateStart.set(Calendar.YEAR, year);
		dateStart.set(Calendar.MONTH, monthOfYear);
		dateStart.set(Calendar.DAY_OF_MONTH, dayOfMonth);
		btnActivityStartDate.setText(Integer.toString(year) + "-" + Integer.toString(monthOfYear + 1) + "-" + Integer.toString(dayOfMonth));
	}

	private void updateStartTime(Calendar cal) {
		updateStartTime(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));
	}

	private void updateStartTime(int hourOfDay, int minute) {
		dateStart.set(Calendar.HOUR_OF_DAY, hourOfDay);
		dateStart.set(Calendar.MINUTE, minute);
		btnActvityStartTime.setText(pad(hourOfDay) + ":" + pad(minute));
	}

	// 时间为个位时在时间前补0
	public static String pad(int c) {
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.schedule_activity_menu_items, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.menu_save) {
			sendActivity();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private void sendActivity() {
		if (saveData()) {
			if (!etActivityAnticipator.getText().toString().equals("")) {
				for (Contact c : mSelectedContact) {

					Message msgToSend = new Message(c.getJIDWithRes(), Message.MSG_TYPE_CHAT);

					msgToSend.setBody(generateSendMessage());

					try {
						IChat mChat = mChatManager.getChat(c);
						if (mChat == null) {
							mChat = mChatManager.createChat(c, null);
						}
						mChat.setOpen(false);
						mChat.sendMessage(msgToSend);

					} catch (RemoteException e) {
						Log.e(TAG, e.getMessage());
					}

				}

			}
			closeActivity(dataTableActivity);
		}

	}

	private String generateSendMessage() {
		StringBuffer mMsgContent = new StringBuffer();
		mMsgContent.append("[活动精灵]").append("活动编号:" + lNewRowId + "\n").append("活动:" + etActvitySubject.getText().toString() + "\n")
				.append("地点:" + etActivityLocaiton.getText().toString() + "\n")
				.append("时间:" + dateStart.get(Calendar.YEAR) + "-" + (dateStart.get(Calendar.MONTH) + 1) + "-" + dateStart.get(Calendar.DAY_OF_MONTH))
				.append("(" + dateStart.get(Calendar.HOUR_OF_DAY) + ":" + dateStart.get(Calendar.MINUTE) + ")" + "\n")
				.append("模式:" + getResources().getStringArray(R.array.ringerMode)[dataRowActivity.getRingerMode()] + "\n")
				.append("闹铃:" + (dataRowActivity.getAlarm() ? "是" : "否") + "\n").append("重复:" + getRepeatInfo() + "\n")
				// .append("参与人:" + etActivityAnticipator.getoText().toString()
				// +
				// "\n")
				.append("请按格式:活动编号_是/否 回复");
		return mMsgContent.toString();
	}

	private void updateRepeatInfo() {
		btnActivityRepeat.setText(getRepeatInfo());
	}

	private String getRepeatInfo() {
		String s = utils.getResStr(R.string.strRepeatTypeNone);
		String sUntil = utils.getResStr(R.string.strRepeatInfoUntil);
		String sEndDate = (dateEndOn.getTimeInMillis() == 0) ? "" : " " + sUntil + " " + utils.getLongDate(dateEndOn);
		// daily
		if (iRepeatType == 1)
			s = String.format(utils.getResStr(R.string.strRepeatInfoDaily), iRepeatEvery, sEndDate);
		// weekly
		if (iRepeatType == 2)
			s = String.format(utils.getResStr(R.string.strRepeatInfoWeekly), iRepeatEvery, sEndDate);
		// monthly
		if (iRepeatType == 3)
			s = String.format(utils.getResStr(R.string.strRepeatInfoMonthly), iRepeatEvery, sEndDate);
		// yearly
		if (iRepeatType == 4)
			s = String.format(utils.getResStr(R.string.strRepeatInfoYearly), sEndDate);
		return s;
	}

	public boolean saveData() {
		// check date if no repeat
		if ((iRepeatType == 0) && (dateBeforeNow(dateStart)))
			return false;

		dataRowActivity.setSubject(etActvitySubject.getText().toString());
		dataRowActivity.setLocation(etActivityLocaiton.getText().toString());
		dataRowActivity.setOrganizer(sOrganizer);
		dataRowActivity.setStartDate(dateStart);
		dataRowActivity.setAlarm(cbActivityAlarm.isChecked());
		dataRowActivity.setRingerMode(iRingerMode);
		dataRowActivity.setSnooze(iSnooze);
		dataRowActivity.setSnoozeCount(iSnoozeCount);
		dataRowActivity.setActionClear(iActionClear);
		// set repeat type
		RepeatData rd = dataRowActivity.getRepeat();
		rd.setRepeatTypeAsInt(iRepeatType);
		rd.setEvery(iRepeatEvery);
		rd.setEndOnDate(dateEndOn.getTimeInMillis());

		return saveDataToTable(dataTableActivity);

	}

	public boolean dateBeforeNow(Calendar calDate) {
		Calendar calNow = Calendar.getInstance();
		if (calNow.get(Calendar.YEAR) == calDate.get(Calendar.YEAR))
			if (calNow.get(Calendar.MONTH) == calDate.get(Calendar.MONTH))
				if (calNow.get(Calendar.DAY_OF_MONTH) == calDate.get(Calendar.DAY_OF_MONTH))
					return false;
		if (calDate.before(calNow)) {
			utils.showMsgResStr(R.string.infoEnterValidDate, Utils.MSGTYPE_INFO);
			return true;
		}
		return false;
	}

	public boolean saveDataToTable(DataTable data) {
		boolean bSuccess = false;
		// update data into database
		if (data.getDataRow().validate()) {

			boolean bInsertMode = (getStartMode() == StartMode.NEW);
			long lRowId = requestedRowId();
			Database.Result result = data.updateData(bInsertMode, lRowId);
			lNewRowId = dataTableActivity.getNewRowId();
			if (result == Database.Result.Success) {
				// AlarmsManager.ResetAlarm(userdb, prefs, data, lRowId);
				if (getStartMode() == StartMode.NEW && mSelectedContact != null) {

					for (Contact contact : mSelectedContact) {
						Log.v(TAG, "lNewRowId:" + lNewRowId);
						dataRowActivityParticipator.setActivityID(lNewRowId);
						dataRowActivityParticipator.setParticipatorPhone(contact.getJID().toLowerCase());
						dataRowActivityParticipator.setParticipatorName(contact.getName());
						dataRowActivityParticipator.setOther(true);
						dataRowActivityParticipator.setReply(2);
						dataRowActivityParticipator.setValuesForDataRow();
						dataTableActivityParticipator.insertValues();

					}
				}
				bSuccess = true;
			} else {
				utils.showMsgResStr(Database.getErrDesc(result), Utils.MSGTYPE_ERROR);

			}
		} else {
			utils.showMsgResStr(R.string.infoEnterAllRequiredData, Utils.MSGTYPE_INFO);
			Log.v("ActivityFairy", "SaveActivity Result:" + 3);
		}
		Log.v("ActivityFairy", "SaveActivity Result:" + bSuccess);
		return bSuccess;
	}

	public void openRepeatDialog() {
		ActivityRepeat.openRepeatForEdit(this, bundleOtherDataStartup, iRepeatType, iRepeatEvery, dateEndOn.getTimeInMillis());
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == Activity.RESULT_OK) {
			Bundle extras = data.getExtras();
			if (extras != null) {
				switch (requestCode) {
				case ActivityRepeat.SELECT_REPEAT_REQUEST:
					if (ActivityRepeat.getActivityResult(requestCode, resultCode, extras)) {
						iRepeatType = ActivityRepeat.getExtraRepeatType(extras);
						iRepeatEvery = ActivityRepeat.getExtraRepeatEvery(extras);
						dateEndOn.setTimeInMillis(ActivityRepeat.getExtraRepeatEndOnDate(extras));
						updateRepeatInfo();

					}
					break;
				case REQUESTCODE_CONTACTS:

					mSelectedContact = data.getParcelableArrayListExtra(ScheduleContactFragment.RESULT_SELECTED_PARTICIPATOR);
					setContacts();
					break;
				}
				// check for repeat update

			}
		} else {
			switch (requestCode) {
			case REQUESTCODE_CONTACTS:
				Log.v(TAG, "REQUESTCODE_CONTACTS");
				break;
			}
		}

	}

	private void setContacts() {
		StringBuilder participatorNames = new StringBuilder();

		for (Contact contact : mSelectedContact) {
			participatorNames.append(contact.getName() + ";");

		}
		etActivityAnticipator.setText(participatorNames.toString());
	}

	private void setContacts(List<DataViewItem> rowsForTotal) {
		StringBuilder participatorNames = new StringBuilder();
		for (DataViewItem dataViewItem : rowsForTotal) {
			DataViewItemActivityParticipator dataViewItemActivityParticipator = (DataViewItemActivityParticipator) dataViewItem;
			participatorNames.append(dataViewItemActivityParticipator.getParticipatorName());
		}
		etActivityAnticipator.setText(participatorNames.toString());
	}

	private class GtalkServiceConnection implements ServiceConnection {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mXmppFacade = IXmppFacade.Stub.asInterface(service);

			try {
				mChatManager = mXmppFacade.getChatManager();

			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mXmppFacade = null;
			mChatManager = null;
		}

	};

}
